<template>
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <!-- 头像上传 -->
        <el-form-item label="头像">
            <el-upload class="avatar-uploader" action="http://localhost:9090/admin/system/file/upload"
                :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                <img v-if="form.headUrl" :src="form.headUrl" class="avatar" />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
        </el-form-item>

        <!-- 其他表单项 -->
        <el-form-item label="用户名" prop="username">
            <el-input v-model.trim="form.username" disabled />
        </el-form-item>

        <el-form-item label="姓名" prop="name">
            <el-input v-model.trim="form.name" />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
            <el-input v-model.trim="form.email" />
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
            <el-input v-model.trim="form.phone" />
        </el-form-item>

        <el-form-item>
            <el-button type="primary" :loading="submitting" @click="submitForm">
                {{ submitting ? '提交中...' : '保存修改' }}
            </el-button>
        </el-form-item>
    </el-form>
</template>

<script>
import api from '@/api/system/sysUser'

export default {
    name: 'ProfileIndex',
    props: {
        user: {
            type: Object,
            default: () => ({})
        }
    },
    data() {
        return {
            form: {},
            submitting: false,
            rules: {
                name: [
                    { required: true, message: '请输入姓名', trigger: 'blur' },
                    { min: 2, max: 20, message: '长度在2到20个字符', trigger: 'blur' }
                ],
                email: [
                    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
                ],
                phone: [
                    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
                ]
            }
        }
    },
    watch: {
        user: {
            immediate: true,
            handler(val) {
                this.form = { ...val }
            }
        }
    },
    methods: {
        // 获取当前用户最新数据
        fetchCurrentUser() {
            try {
                api.getCurrentUser().then(res => {
                    if (res.code === 200) {
                        this.form = { ...res.data }
                        // 更新Vuex状态
                        this.$store.dispatch('user/updateUser', this.form)
                    }
                })
            } catch (error) {
                console.error('获取用户信息失败:', error)
            }
        },
        // 头像上传成功处理
        handleAvatarSuccess(res) {
            if (res.code === 200) {
                try {
                    // 立即更新头像到数据库
                    api.updateAvatar(res.data.url).then(res => {
                        if (res.code === 200) {
                            // 刷新本地数据
                            this.fetchCurrentUser()
                            this.$message.success('头像更新成功')
                        }
                    })
                } catch (error) {
                    this.$message.error('头像更新失败' + error.message)
                }
            }
        },
        beforeAvatarUpload(file) {
            const isImage = file.type.startsWith('image/')
            const isLt2M = file.size / 1024 / 1024 < 2

            if (!isImage) {
                this.$message.error('只能上传图片文件!')
            }
            if (!isLt2M) {
                this.$message.error('头像大小不能超过2MB!')
            }
            return isImage && isLt2M
        },

        // 提交表单
        async submitForm() {
            this.submitting = true
            try {
                const valid = await this.$refs.formRef.validate()
                if (!valid) return

                api.updateUser(this.form).then(res => {
                    if (res.code === 200) {
                        this.submitting = false
                        this.fetchCurrentUser() // 刷新最新数据
                        this.$message.success('资料更新成功')
                    }
                })
            } catch (error) {
                this.submitting = false
                console.error('更新失败:', error)
            }
        },
    }
}
</script>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
}

.avatar {
    width: 120px;
    height: 120px;
    display: block;
}
</style>